package com.google.gwt.sample.dynatable.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: denis_zavadsky
 * Date: 9/14/13
 * Time: 11:21 AM
 * To change this template use File | Settings | File Templates.
 */
public class LocationWidget extends HorizontalPanel{

    private final ListBox countryListBox = new ListBox();
    private final ListBox cityListBox = new ListBox();
    private final LocationServiceAsync locationService;

    public LocationWidget() {
        locationService = GWT.create(LocationService.class);
        init();

    }

    private void init(){
        this.setWidth("400px");
        this.setHeight("200px");
        countryListBox.setTitle("Country");
        cityListBox.setTitle("City");
        locationService.getAllCountries(new AsyncCallback<List<Country>>() {
            @Override
            public void onFailure(Throwable caught) {
                Window.alert("ERROORRRRR");
            }

            @Override
            public void onSuccess(List<Country> result) {
                populateCountryListBox(result);
            }
        });
        countryListBox.addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                String countryId = countryListBox.getValue(countryListBox.getSelectedIndex());
                locationService.getCityByCountryId(Long.parseLong(countryId),new AsyncCallback<List<City>>() {
                    @Override
                    public void onFailure(Throwable caught) {
                        Window.alert("ERROORRRRR");
                    }

                    @Override
                    public void onSuccess(List<City> result) {
                        populateCityListBox(result);
                    }
                });
            }
        });

        this.add(countryListBox);
        this.add(cityListBox);
    }

    private void populateCityListBox(List<City> result) {
        cityListBox.clear();
        for (City c: result){
            cityListBox.addItem(c.getName(),c.getId().toString());
        }
    }

    private void populateCountryListBox(List<Country> countries) {
        countryListBox.clear();
         for (Country c: countries){
             countryListBox.addItem(c.getName(),c.getId().toString());

         }
    }
}
